package servlets;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;

import beans.Usuario;


public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public LoginServlet() {
        super();
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processaLogin(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processaLogin(request, response);
	}
	
	@SuppressWarnings("unchecked")
	public void processaLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		String email = request.getParameter("email");
		String senha = request.getParameter("senha");

		Usuario usuario = new Usuario();
		usuario.setEmail(email);
		usuario.setSenha(senha);

		ArrayList<Usuario> listaDeUsuarios = null;
		boolean jaExiste = false;
		
		String path = getServletContext().getRealPath("/bancodados/login.obj");
		
		Usuario user = null;
		try {
			
			FileInputStream fis = new FileInputStream(path);
			ObjectInputStream ois = new ObjectInputStream(fis);
			listaDeUsuarios = (ArrayList<Usuario>) ois.readObject();
			ois.close();
			for (Usuario u : listaDeUsuarios) {
				if(u.getEmail().equals(usuario.getEmail())){
					jaExiste = true;
					user = u;
					break;
				}				
			}
		} catch (Exception e) {
		}
		
		String url = "";
		HttpSession session = request.getSession();
		
		if(!jaExiste){
			JOptionPane.showMessageDialog(null,"Não existe cadastro com esse email. Cadastre-se." );
			url = "/cadastrousuario.jsp"; 
		}else if(!user.getSenha().equals(senha)){
			JOptionPane.showMessageDialog(null,"Senha não confere com o usuario." );
			url="/login.jsp?user="+email;
		}
		else{
			session.setAttribute("usuario", usuario);
			String urlRequerida = (String) session.getAttribute("url");
			
			if(urlRequerida != null){
				url = urlRequerida;
				session.removeAttribute("url");
			}else{
				url = "/index.jsp";
			}
		}
		
		response.sendRedirect(request.getContextPath() + url);

		//RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		//dispatcher.forward(request, response);
		
	}

}
